<template>
  <div class="biz-container">
    <table-layout :haveSider="false">
      <template #headCustom>
        <a-steps
          :current="0"
          style="margin:10px 0"
          size="small"
        >
          <a-step title="完善配送商品明细" />
          <a-step title="完善发票" />
          <a-step title="完善配送单信息" />
          <a-step title="预览并提交" />
        </a-steps>
      </template>
      <template #batchOperat>
      </template>
      <template #tableList="slotData">
        <a-row
          style="width:100%"
          type="flex"
        >
          <a-col flex="150px">
            <span style="fontSize:20px;color:#027bd9">配送商品明细</span>
          </a-col>
          <a-col
            flex="auto"
            class="batchInput"
          >
            <search-layout
              :formInfos="i_formInfos"
              :formDatas="i_formDatas"
              message=""
              @onFind="onFill"
            ></search-layout>
          </a-col>
        </a-row>
        <a-list-table
          tableId="goodsTable1"
          :columns="columns"
          :tableData="listdata"
          :haveChild="true"
          :pagination="pagination"
          :isSelecttion="false"
          :isInnerSelecttion="true"
          @onInnerSelect="onInnerSelect"
          :loading="loading"
          :scroll="{y:slotData.tableHeight-60}"
          @onTableChange="handleTableChange"
          @onselectChange="onselectChange"
          @onAction="onAction"
          @expand="onExpand"
          :links="links"
          :autoComputed="autoComputed"
          @onTouchlinkCell="onTouchlinkCell"
          :innerTable="innerTable"
          @onInnerAction="onInnerAction"
          @onInnerChangeInput="onInnerChangeInput"
          @clearSelect="clearSelect"
        >
          <!-- <template #innerTable>
                <a-list-table
                slot="expandedRowRender" slot-scope="record"
                :columns="innerTable.innerColumns"
                :tableData="record"
                size="small"
                :isSelecttion="undefined"
                :loading="innerTable.innerLoading"
                :inputNameObj="innerTable.innerInputName"
                @onChangeInput="onChangeInput"
                @onAction="onInnerAction"
                >
                </a-list-table>
            </template> -->
        </a-list-table>
        <div style="height:40px;textAlign:center;marginTop:10px">
          <a-button
            type="primary"
            @click="onNext"
          >下一步</a-button>
        </div>
      </template>

    </table-layout>
    <toDeliveryModal
      ref="modal"
      @ok="handleModalSaveOk"
      @close="handleModalCancel"
    />
    <!-- <viewModal ref="viewModal" @ok="handleModalSaveOk" @close="handleModalCancel" /> -->
    <viewSaleOrderModal
      ref="viewSaleOrderModal"
      @ok="handleModalSaveOk"
      @close="handleModalCancel"
    />
  </div>
</template>

<script>
import searchLayout from '@/views/app/biz/common/searchLayout'
import batchOperatBtn from '@/views/app/biz/common/batchOperatBtn'
import tableLayout from '@/views/app/biz/common/index'
import aListInfo from '@/views/app/biz/common/aListInfo'
import aListTable from '@/views/app/biz/common/aListTable'
import toDeliveryModal from './toDeliveryModal'
import viewSaleOrderModal from '../saleOrder/viewModal.vue'
// import viewModal from './viewModal'
import {
  getMergeByConditions,
  getDetailByConditionsCount,
  checkDetailNum
} from './saleDelivery'


const columns = [
  { title: '品名', dataIndex: 'productNameZh', key: 'productNameZh', align: 'center', },
  { title: '通用名', dataIndex: 'commonName', key: 'commonName', align: 'center', scopedSlots: { customRender: 'commonName' } },
  { title: '生产企业名称', dataIndex: 'manufacturerZh', key: 'manufacturerZh', align: 'center', },
  { title: '规格', dataIndex: 'spec', key: 'spec', align: 'center' },
  { title: '型号', dataIndex: 'model', key: 'model', align: 'center' },
  { title: '计量单位', dataIndex: 'measurement', key: 'measurement', align: 'center' },
  { title: '需配送数量', dataIndex: 'num', key: 'num', align: 'center', scopedSlots: { customRender: 'num' } },
  { title: '单价(元)', dataIndex: 'iunitprice', key: 'iunitprice', align: 'center', scopedSlots: { customRender: 'iunitprice' } },
  { title: '配送数量', dataIndex: 'execNum', key: 'execNum', align: 'center', scopedSlots: { customRender: 'execNum' } },
  { title: '总价(元)', dataIndex: 'totalPrice', key: 'totalPrice', align: 'center', scopedSlots: { customRender: 'totalPrice' } },
  { title: '操作', dataIndex: 'action', key: 'operation', width: 180, align: 'center', scopedSlots: { customRender: 'action' } },
]
let links = ['saleOrderNo',]
let autoComputed = ['execNum', 'totalPrice']
let inputNameObj = [
  { name: 'commonName', type: 'text', placeholder: '通用名' },
]
export default {
  components: {
    searchLayout,
    batchOperatBtn,
    tableLayout,
    aListInfo,
    aListTable,
    viewSaleOrderModal,
    // viewModal, 
    toDeliveryModal
  },
  props: {
    conditions: {
      type: Array,
      default: () => {
        return []
      }
    }
  },
  data () {
    return {
      //批量填入表单
      i_formInfos: [
        { label: '', name: 'batchCode', type: 'input', isDisabled: true, placeholder: '批号' },
        // {label: '',name:'execNum',type:'number',isDisabled:true,placeholder:'数量'},
        { label: '', name: 'productDate', type: 'productDate', isDisabled: true, placeholder: '生产日期' },
        { label: '', name: 'expiryDate', type: 'expiryDate', isDisabled: true, placeholder: '有效期' },
        { label: ['批量填入',], type: 'botton' }
      ],
      i_formDatas: {
        // execNum: null,
        batchCode: null,
        productDate: null,
        expiryDate: null
      },
      columns: columns,
      listdata: [],
      links: links,
      autoComputed: autoComputed,
      inputNameObj: inputNameObj,
      loading: false,
      pagination: {
        //分页配置
        current: 1, //当前页码 current
        pageSize: 100000, //每页显示条数 pageSize
        total: 1,
        // showQuickJumper: true,
        // showSizeChanger: true,
        // pageSizeOptions: ['2', '10', '50', '100'],
      },
      // 查询表单
      q_formInfos: [
        { label: '销售单号', name: 'saleOrderNo', type: 'input', placeholder: '销售单号' },
        { label: '客户名称', name: 'customerName', type: 'customer', placeholder: '客户名称' },
        { label: ['查询', '重置'], type: 'botton' }
      ],
      // 查询表单绑定数据
      q_formDatas: {
        saleOrderPid: "4a421c5e8bc2444b981c575584d94299",
        // saleOrderNo: null,
        // customerName: null,
        // saleOrderState:'待配送'
      },
      pData: {}, // 条件查询参数
      isJump: false,
      optText: '确认订单',
      selectedRowKeys: [],
      selectedRows: [],
      listdata_sel: [],
      notAudit: false,
      innerTable: {
        innerColumns: [
          { title: '销售单号', dataIndex: 'saleOrderNo', key: 'saleOrderNo', align: 'center' },
          { title: '品名', dataIndex: 'productNameZh', key: 'productNameZh', align: 'center', },
          { title: '通用名', dataIndex: 'commonName', key: 'commonName', align: 'center' },
          // { title: '生产企业名称', dataIndex: 'manufacturerZh', key: 'manufacturerZh', align: 'center', },
          { title: '规格', dataIndex: 'spec', key: 'spec', align: 'center' },
          // { title: '型号', dataIndex: 'model', key: 'model', align: 'center' },
          { title: '计量单位', dataIndex: 'measurement', key: 'measurement', align: 'center' },
          { title: '需配送数量', dataIndex: 'num', key: 'num', align: 'center', scopedSlots: { customRender: 'num' } },
          { title: '单价(元)', dataIndex: 'iunitprice', key: 'iunitprice', align: 'center', scopedSlots: { customRender: 'iunitprice' } },
          { title: '批号', dataIndex: 'batchCode', key: 'batchCode', align: 'center', width: '140px', scopedSlots: { customRender: 'batchCode' } },
          { title: '生产日期', dataIndex: 'productDate', key: 'productDate', align: 'center', width: '140px', scopedSlots: { customRender: 'productDate' } },
          { title: '有效期', dataIndex: 'expiryDate', key: 'expiryDate', align: 'center', width: '140px', scopedSlots: { customRender: 'expiryDate' } },
          { title: '配送数量', dataIndex: 'execNum', key: 'execNum', align: 'center', width: '100px', scopedSlots: { customRender: 'execNum' } },
          { title: '操作', dataIndex: 'action', key: 'operation', width: 150, align: 'center', scopedSlots: { customRender: 'action' } },
        ],
        innerInputName: [
          { name: 'execNum', type: 'number', placeholder: '数量' },
          { name: 'batchCode', type: 'text', placeholder: '批号' },
          { name: 'productDate', type: 'productDate', placeholder: '生产日期' },
          { name: 'expiryDate', type: 'expiryDate', placeholder: '有效期' },
        ],
        innerData: [],
        innerLoading: false,
      }
    }
  },
  watch: {
    listdata: {
      handler: function (val, oldVal) {
        console.log("$$$$$$$$");

      },
      deep: true,
      immediate: true
    },
  },
  computed: {},
  created () {

  },
  updated () {
    console.log("&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&");
  },

  mounted () {
    let condition = ''
    for (const item of this.conditions) {
      condition = condition + item.saleOrderNo + ','
    }
    // this.getTotal()
    const pa = {
      'saleOrders': condition
    }
    console.log('请求列表时传入的数据', pa)
    this.getList(pa)
    this.initSelect()
  },
  methods: {
    // 初始化页面时得到总数
    async getTotal () {
      let pages = ''
      pages = await getDetailByConditionsCount(this.q_formDatas)
      console.log(pages)
      if (pages && pages.code && pages.code === 'C1') {
        const pagination = { ...this.pagination }
        pagination.total = pages.data
        this.pagination = pagination
        this.pagination.showTotal = (showTotal) => { return `共 ${showTotal} 条` }
      }
    },
    setPage (list) {
      const pagination = { ...this.pagination }
      pagination.total = list.length
      this.pagination = pagination
      this.pagination.showTotal = (showTotal) => { return `共 ${showTotal} 条` }
    },
    // 初始化查询时的数据列表
    async getList (params) {
      console.log('请求列表时传入的数据', params)
      let actionBtn = ['删除']
      this.loading = true
      this.listdata = []
      let res = ''
      res = await getMergeByConditions(params, this.pagination)
      this.loading = false
      console.log(res)
      if (res && res.code && res.code === 'C1' && res.data) {
        const resdata = res.data
        for (let id in resdata) {
          for (const item of resdata[id].child) {
            item.key = item.pid
            item.execNum = item.execNum ? item.execNum : null
            item.batchCode = item.batchCode ? item.batchCode : null
            item.productDate = item.productDate ? item.productDate : null
            item.expiryDate = item.expiryDate ? item.expiryDate : null
            item.action = ['添加', '删除']
          }
          this.listdata.push({
            key: id,
            action: actionBtn,
            selectedRowKeys: [],
            child: resdata[id].child,
            ...resdata[id].saleOrderDetail,

          })
        }
      } else {
        this.listdata = []
      }
      this.setPage(this.listdata)
      console.log(this.listdata)
    },
    // 关闭模态详细框
    handleModalCancel () {
    },
    // 模态详细框提交按钮
    handleModalSaveOk () {
      this.getList(this.q_formDatas)
    },
    // 操作按钮
    onAction (text, record, index) {
      if (text == '删除') {
        let that = this
        this.$confirm({
          title: '是否确认删除？',
          content: '删除后不可恢复！',
          onOk () {
            console.log(that.listdata);
            that.listdata.splice(index, 1)
            that.clearSelect(record)
          },
          onCancel () { },
        });
      }
    },
    onInnerAction (text, record, index) {
      if (text == '删除') {
        this.delInnerItem(text, record, index)
      } else if (text == '添加') {
        this.addInnerItem(text, record, index)
      } else if (text == '移除') {
        this.removeInnerItem(text, record, index)
      }
    },
    addInnerItem (text, record, index) {
      console.log(record);
      let parentItem = this.listdata.find(item => { return item.saleGoodsPid == record.saleGoodsPid })
      let newRecord = JSON.parse(JSON.stringify(record))
      newRecord.action = ['移除']
      newRecord.execNum = null
      newRecord.batchCode = null
      newRecord.productDate = null
      newRecord.expiryDate = null
      newRecord.key = new Date().getTime()
      let optInd = parentItem.child.findIndex(item => { return item.key == record.key })
      parentItem.child.splice(optInd + 1, 0, newRecord)
      this.clearSelect(record)
    },
    removeInnerItem (text, record, index) {
      console.log(record);
      let parentItem = this.listdata.find(item => {
        return item.saleGoodsPid == record.saleGoodsPid
      })
      parentItem.child.splice(index, 1)
      this.clearSelect(record)
    },
    delInnerItem (text, record, index) {
      let that = this
      this.$confirm({
        title: '是否确认删除？',
        content: '删除后不可恢复！',
        onOk () {
          console.log(record);
          let parentItem = that.listdata.find(item => {
            return item.saleGoodsPid == record.saleGoodsPid
          })
          parentItem.child.splice(index, 1)
          that.clearSelect(record)
        },
        onCancel () { },
      });
    },
    // 触发改变页码,筛选,排序时的回调
    handleTableChange (pagination, filters, sorter) {
      this.pagination.current = pagination.current
      this.pagination.pageSize = pagination.pageSize
      this.getList(this.q_formDatas)
    },
    //点击展开表格
    onExpand (expanded, record) {
      console.log(expanded, record);
    },
    onInnerChangeInput (target, value, key, column, index) {

    },
    // 查询按钮
    onFill () {
      for (let item of this.listdata) {
        if (item.selectedRowKeys.length) {
          for (let itemc of item.child) {
            let isInSelArr = item.selectedRowKeys.find(ite => {
              return ite == itemc.key
            })
            console.log(isInSelArr);
            if (isInSelArr) {
              // itemc.execNum=this.i_formDatas.execNum
              itemc.batchCode = this.i_formDatas.batchCode
              itemc.productDate = this.i_formDatas.productDate
              itemc.expiryDate = this.i_formDatas.expiryDate
            }
          }
        }

        item.selectedRowKeys = []
      }
      this.listdata = [...this.listdata]
      this.setDisable()
      // this.initSelect(null)
    },

    onTouchlinkCell (text, record, index, link) {
      console.log(record);
      if (link == 'saleOrderNo') {
        this.$refs.viewSaleOrderModal.showModal(record.pid, record)
      }
    },
    // 多选批量操作
    onselectChange (selectedRowKeys, selectedRows) {
      this.selectedRowKeys = selectedRowKeys
      this.selectedRows = selectedRows
      for (const item of this.selectedRows) {
        if (item.action[0] != '确认') {
          this.notAudit = true
          return
        } else {
          this.notAudit = false
        }
      }
    },
    // 子表格多选批量操作
    onInnerSelect (selectedRowKeys, selectedRows, record) {
      console.log("*************************************");
      console.log(selectedRowKeys, selectedRows, record);

      let parScdind = this.listdata.findIndex(item => {
        return item.pid == record.pid
      })
      this.listdata[parScdind].selectedRowKeys = selectedRowKeys
      this.setDisable()
    },
    clearSelect (record) {
      console.log(record);
      console.log("____________________________________");
      this.initSelect(record)
    },
    initSelect (record) {//purProdPid
      for (let item of this.listdata) {
        console.log(record);
        if (record.purProdPid == item.purProdPid) {
          item.selectedRowKeys = []
        }
      }
      this.listdata = [...this.listdata]
      this.setDisable()
    },
    setDisable () {
      //循环数组，如果有选择，则批量栏可填
      let haveSel = false
      for (let item of this.listdata) {
        if (item.selectedRowKeys.length) {
          haveSel = true
        }
      }
      for (let el of this.i_formInfos) {
        if (haveSel) {
          el.isDisabled = false
        } else {
          el.isDisabled = true
        }
      }
      this.i_formInfos = [...this.i_formInfos]
    },
    onBatchAudit () {
      if (this.selectedRows.length) {
        if (this.notAudit) {
          this.$message.warning({ content: '已选项中含有已确认的记录，请选择未确认的记录', duration: 3 })
        } else {
          this.showConfirm(this.selectedRows)
        }
      } else {
        this.$message.warning({ content: '未选择要审核的记录', duration: 3 })
      }
    },
    onNext () {
      console.log(this.listdata);
      let next = true
      if (this.listdata.length) {
        outloop:
        for (const item1 of this.listdata) {
          for (const item2 of item1.child) {
            if (!item2.batchCode) {
              this.$message.warning({ content: '商品批号不能为空', duration: 3 })
              next = false
              break outloop;
            }
            if (!item2.execNum) {
              this.$message.warning({ content: '配送数量必须大于0', duration: 3 })
              next = false
              break outloop;
            }
            if (!item2.productDate) {
              this.$message.warning({ content: '生产日期不能为空', duration: 3 })
              next = false
              break outloop;
            }
            if (!item2.expiryDate) {
              this.$message.warning({ content: '有效期不能为空', duration: 3 })
              next = false
              break outloop;
            }
          }

        }
        if (next) {
          this.checkDetailNum(this.listdata)
        }
      } else {
        this.$message.warning({ content: '未添加商品信息', duration: 3 })
      }
    },
    async checkDetailNum (sbData) {
      let sData = {
        deliveryOrderDetails: sbData
      }
      let res = await checkDetailNum(sData)
      console.log(res);
      if (res && res.code == "C1") {
        if (res.data > 0) {
          this.$message.warning({ content: '明细数量有误' })
        } else {
          this.$emit('onNextStep', this.listdata)
        }

      } else {
        this.$message.error({ content: '请求出错' + res.message })
      }
    }
  },
}
</script>

<style>
.batchInput {
  display: flex;
  justify-content: right;
  align-items: center;
}
</style>